/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.project.carshop07.core;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author EGHOS
 */
@XmlRootElement
public class ShoppingCart {
    
    @XmlElement(name ="orderItem")
    private final List<OrderItem> items = new ArrayList<OrderItem>();
    
    @XmlElement(name ="total")
    private BigDecimal tot;
    
    @XmlTransient
    public List<OrderItem> getItems() {
        return items;
    }

    public BigDecimal getTotal() {
        double total = 0;
        for (OrderItem i : items) {
            total += i.getCost();
        }
        return BigDecimal.valueOf(Math.round(total));
    }
    
    public void calculateTotal(){      
        tot = getTotal();
    }
    
    public void addItem(OrderItem item) {
        addItem(item.getProduct());
    }
    
    public void addItem(Car item) {
        for (OrderItem i : items) {
            if (i.getProduct().getId().equals(item.getId())) {
                //i.setQuantity(i.getQuantity() + 1); quantity is unused
                return;
            }
        }
        items.add(new OrderItem(1, item));
    }
    
    public void emptyCart(){
        items.clear();
    }
    public void removeItem(Long id) {
        OrderItem toDelete = null;
        for (OrderItem i : items) {
            if (i.getProduct().getId().equals(id)) {
                //i.setQuantity(i.getQuantity() - 1); quantity is unused
                //return;
            //} else {
                toDelete = i; // No concurrent modification!
                break;
            }
        }
        items.remove(toDelete);
    }

    // TODO Simple solution for now (use by Mail)
    @Override
    public String toString() {
        StringBuilder b = new StringBuilder();
        for (OrderItem i : items) {
            b.append(i.getProduct().getMake()).append(" ").append(i.getQuantity()).
                    append(" ").append(i.getCost()).append("\n");
        }
        b.append("Total ").append(getTotal());
        return b.toString();
    }
}
